package com.neusoft.demo3.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.neusoft.demo3.bean.Cart;
import com.neusoft.demo3.bean.SysOrder;
import com.neusoft.demo3.config.AjaxResult;
import com.neusoft.demo3.mapper.CartMapper;
import com.neusoft.demo3.mapper.SysOrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.util.*;

@RestController
@RequestMapping("/sysOrder")
public class SysOrderController {
    @Autowired
    private SysOrderMapper sysOrderMapper;
    @Autowired
    private CartMapper cartMapper;

    @GetMapping("Orderlist")
    public Object findall(@RequestParam Integer userId) {
        try {
            QueryWrapper<SysOrder> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId);
            List<SysOrder> orderList = sysOrderMapper.selectList(queryWrapper);
            return AjaxResult.success(orderList);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.exception("查询订单失败");
        }
    }

    @PostMapping("create")
    public AjaxResult createOrder(@RequestParam Integer userId) {
        try {
            System.out.println("=== 开始创建订单 ===");
            System.out.println("用户ID: " + userId);

            // 使用正确的查询方式
            QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId);
            queryWrapper.select("goods_id", "goods_name", "goods_price", "goods_num", "goods_img");

            List<Cart> cartItems = cartMapper.selectList(queryWrapper);

            System.out.println("查询到的购物车商品数量: " + cartItems.size());

            // 检查购物车是否为空
            if (cartItems.isEmpty()) {
                return AjaxResult.error("购物车为空，请先添加商品到购物车");
            }

            // 打印购物车中的真实商品信息
            System.out.println("=== 购物车中的商品 ===");
            for (Cart cartItem : cartItems) {
                System.out.println("商品ID: " + cartItem.getGoodsId());
                System.out.println("商品名称: " + cartItem.getGoodsName());
                System.out.println("商品价格: " + cartItem.getGoodsPrice());
                System.out.println("商品数量: " + cartItem.getGoodsNum());
                System.out.println("商品图片: " + cartItem.getGoodsImg());
                System.out.println("---");
            }

            // 构建商品信息JSON（使用购物车中的真实数据）
            List<Map<String, Object>> goodsList = new ArrayList<>();
            double totalAmount = 0.0;

            for (Cart cartItem : cartItems) {
                Map<String, Object> goods = new HashMap<>();
                goods.put("goodsId", cartItem.getGoodsId());
                goods.put("goodsName", cartItem.getGoodsName());
                goods.put("goodsPrice", cartItem.getGoodsPrice());
                goods.put("goodsNum", cartItem.getGoodsNum());
                goods.put("goodsImg", cartItem.getGoodsImg() != null ? cartItem.getGoodsImg() : "");
                goodsList.add(goods);

                // 计算总价
                if (cartItem.getGoodsPrice() != null && cartItem.getGoodsNum() != null) {
                    totalAmount += cartItem.getGoodsPrice() * cartItem.getGoodsNum();
                }
            }

            // 转换为JSON字符串
            ObjectMapper objectMapper = new ObjectMapper();
            String goodsInfo = objectMapper.writeValueAsString(goodsList);
            System.out.println("从购物车生成的goodsInfo JSON: " + goodsInfo);

            // 创建订单对象
            SysOrder order = new SysOrder();
            order.setOrderNo("ORD" + System.currentTimeMillis());
            order.setUserId(userId);
            order.setTotal((float) totalAmount);
            order.setGoodsInfo(goodsInfo);
            order.setCreatTime(new Timestamp(System.currentTimeMillis()));

            System.out.println("=== 准备插入的订单信息 ===");
            System.out.println("orderNo: " + order.getOrderNo());
            System.out.println("userId: " + order.getUserId());
            System.out.println("total: " + order.getTotal());
            System.out.println("creatTime: " + order.getCreatTime());

            // 插入订单
            int result = sysOrderMapper.insert(order);
            System.out.println("插入结果: " + result);
            System.out.println("插入后的ID: " + order.getId());

            // 清空购物车和验证数据
            if (result > 0) {
                // 清空购物车
                QueryWrapper<Cart> deleteWrapper = new QueryWrapper<>();
                deleteWrapper.eq("user_id", userId);
                int deleteCount = cartMapper.delete(deleteWrapper);
                System.out.println("清空购物车，删除记录数: " + deleteCount);

                return AjaxResult.success("订单创建成功");
            } else {
                System.out.println("❌ 订单插入失败");
                return AjaxResult.error("订单创建失败");
            }

        } catch (Exception e) {
            System.out.println("❌ 创建订单异常: " + e.getMessage());
            e.printStackTrace();
            return AjaxResult.error("创建订单失败: " + e.getMessage());
        }
    }
    // 查看当前用户的购物车内容
    @GetMapping("viewCart")
    public AjaxResult viewCart(@RequestParam Integer userId) {
        try {
            System.out.println("=== 查看购物车内容 ===");

            // 使用正确的查询方式
            QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId);
            queryWrapper.select("goods_id", "goods_name", "goods_price", "goods_num", "goods_img");

            List<Cart> cartItems = cartMapper.selectList(queryWrapper);

            System.out.println("用户 " + userId + " 的购物车商品数量: " + cartItems.size());

            List<Map<String, Object>> result = new ArrayList<>();
            double total = 0.0;

            for (Cart item : cartItems) {
                Map<String, Object> goods = new HashMap<>();
                goods.put("goodsId", item.getGoodsId());
                goods.put("goodsName", item.getGoodsName());
                goods.put("goodsPrice", item.getGoodsPrice());
                goods.put("goodsNum", item.getGoodsNum());
                goods.put("goodsImg", item.getGoodsImg());
                result.add(goods);

                // 计算小计
                if (item.getGoodsPrice() != null && item.getGoodsNum() != null) {
                    total += item.getGoodsPrice() * item.getGoodsNum();
                }
            }

            Map<String, Object> response = new HashMap<>();
            response.put("cartItems", result);
            response.put("totalCount", cartItems.size());
            response.put("totalAmount", total);

            System.out.println("购物车总金额: " + total);

            return AjaxResult.success(response);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("查看购物车失败: " + e.getMessage());
        }
    }
}